<template>
	<div :class="[prefixCls]" @mouseenter="handleShowPopper" @mouseleave="handleClosePopper">
		<div :class="[prefixCls + '-rel']" ref="reference">
			<slot></slot>
		</div>
		<transition name="fade">
			<div
				:class="[prefixCls + '-popper', prefixCls + '-' + theme]"
				:style="dropStyles"
				ref="popper"
				v-show="!disabled && (visible || always)"
				@mouseenter="handleShowPopper"
				@mouseleave="handleClosePopper"
				:data-transfer="transfer"
				v-transfer-dom
			>
				<div :class="[prefixCls + '-content']">
					<div :class="[prefixCls + '-arrow']"></div>
					<div :class="innerClasses" :style="innerStyles">
						<slot name="content">{{ content }}</slot>
					</div>
				</div>
			</div>
		</transition>
	</div>
</template>
<script lang="ts"> 
	import { Prop, Emit, Component, Watch, Mixins } from "vue-property-decorator";

	import Popper from "../../mixins/popper";
	import TransferDom from "../../directives/transfer-dom";
	import { oneOf } from "../../utils/assist";
	import { transferIndex, transferIncrease } from "../../utils/const";

	const prefixCls = "ivu-tooltip";
	@Component({
		directives: { TransferDom }
	})
	export default class Tooltip extends Popper {
		@Prop({ type: Boolean, default: false }) disabled!: boolean;
		// under this prop,Tooltip will not close when mouseleave
		@Prop({ type: Boolean, default: false }) controlled!: boolean;
		@Prop({ type: Boolean, default: false }) type!: boolean;
		@Prop({ type: Boolean, default: false }) always!: boolean;
		@Prop({ type: Boolean, default: false }) transfer!: boolean;
		@Prop({ type: Number, default: 100 }) delay!: number;
		@Prop({ type: String, default: "" }) content!: string;
		@Prop() maxWidth!: number;
		@Prop({
			type: String,
			default: "dark",
			validator(value) {
				return oneOf(value, ["dark", "light"]);
			}
		})
		theme!: string;
		timeout!: number;
		prefixCls = prefixCls;
		tIndex = this.handleGetIndex();
		mounted() {
			if (this.always) {
				this.updatePopper();
			}
		}

		get innerStyles() {
			const styles: any = {};
			if (this.maxWidth) styles["max-width"] = `${this.maxWidth}px`;
			return styles;
		}
		get innerClasses() {
			return [
				`${prefixCls}-inner`,
				{
					[`${prefixCls}-inner-with-width`]: !!this.maxWidth
				}
			];
		}
		get dropStyles() {
			const styles: any = {};
			if (this.transfer) styles["z-index"] = 1060 + this.tIndex;

			return styles;
		}
		@Watch("content")
		onContentChange() {
			this.updatePopper();
		}

		handleShowPopper() {
			if (this.timeout) clearTimeout(this.timeout);
			this.timeout = setTimeout(() => {
				this.visible = true;
			}, this.delay);
			this.tIndex = this.handleGetIndex();
		}
		handleClosePopper() {
			if (this.timeout) {
				clearTimeout(this.timeout);
				if (!this.controlled) {
					this.timeout = setTimeout(() => {
						this.visible = false;
					}, 100);
				}
			}
		}
		handleGetIndex() {
			transferIncrease();
			return transferIndex;
		}
	}
</script>
